import { login, logout, getUserInfo, getUserByToken, getUserIpCity } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";

const USER_ID = 'USER_ID'

const user = {

    state: {
        token: getToken(),
        userInfo: {
            id: null,
            realName: null,
            account: null,
            mobile: null,
            email: null,
            avatar: null,
            sex: null,
            loginCount: null,
            lastLoginTime: null,
            lastLoginIp: null
        },
        companys: [],
        departments: [],
        roles: [],
        groups: [],
        permissions: [],
        ipCity: {
            country: null,
            region: null,
            city: null,
            area: null,
            isp: null
        }
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_USER_INFO: (state, user) => {
            state.userInfo = user
        },
        SET_COMPANYS: (state, company) => {
            state.companys = company
        },
        SET_DEPARTMENTS: (state, department) => {
            state.departments = department
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_GROUPS: (state, groups) => {
            state.groups = groups
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        },
        CLEAR_USER_INFO: (state) => {
            state.userInfo = Object.assign({}, {id: null, account: null})
        },
        SET_IP_CITY: (state, ipCity) => {
            state.ipCity = Object.assign({}, ipCity)
        }
    },
    actions: {
        // 账号登录（支持用户名，手机号，邮箱）
        Login({ commit, state }, userInfo) {
            const account = userInfo.account.trim()

            return new Promise((resolve, reject) => {
                login(account, userInfo.password).then(response => {
                    const data = response.data.data

                    if(data != undefined && response.data.status) {
                        commit('SET_TOKEN', data.token)
                        window.sessionStorage.setItem(USER_ID, data.id)
                    }
                    resolve(response)
                }).catch(() => {
                    reject({status: false, msg: '登录异常，请联系管理员'})
                })
            })
        },

        //获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                const user_id = window.sessionStorage.getItem(USER_ID)

                if(user_id) {
                    getUserInfo(user_id).then((response) => {
                        const userInfo = response.data
                        const companys = response.data.companys
                        const departments = response.data.departments
                        const roles = response.data.roles
                        const groups = response.data.groups
                        const permissions = response.data.permission

                        delete userInfo.organizations
                        delete userInfo.companys
                        delete userInfo.departments
                        delete userInfo.roles
                        delete userInfo.groups
                        delete userInfo.permission
                        delete userInfo.password
                        delete userInfo.salt

                        commit('SET_USER_INFO', userInfo);
                        commit('SET_COMPANYS', companys)
                        commit('SET_DEPARTMENTS', departments)
                        commit('SET_ROLES', roles)
                        commit('SET_GROUPS', groups)
                        commit('SET_PERMISSIONS', permissions)
                        resolve(userInfo)
                    }).catch((error) => {
                        reject(error)
                    })
                } else {
                    reject()
                }

            });
        },

        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                console.log(123)
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('CLEAR_USER_INFO')
                    window.sessionStorage.removeItem(USER_ID)
                    removeToken()
                    resolve()
                }).catch(() => {
                    reject()
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                commit('SET_TOKEN', '')
                commit('SET_TOKEN', '')
                commit('CLEAR_USER_INFO')
                commit('CLEAR_ADD_ROUTERS')
                window.sessionStorage.removeItem(USER_ID)
                removeToken()
                resolve()
            })
        },

        //获取登录用户的ip所在地理位置
        GetUserIpCity({ commit, state }) {
            if(state.userInfo.lastLoginIp === '127.0.0.1') {
                commit('SET_IP_CITY', {city: '本地'})
            } else {
                return new Promise((resolve, reject) => {
                    getUserIpCity(state.userInfo.lastLoginIp).then(res => {
                        commit('SET_IP_CITY', res.data)
                    })
                })
            }

        }
    }

}

export default user
